package com.chcit.mobile.mvp.common.ui.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatImageView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;

import com.chcit.mobile.app.utils.BarcodeUtil;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.chcit.custom.view.edit.history.SearchLayoutComponent;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.SupportToolbarFragement;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.di.component.DaggerServerComponent;
import com.chcit.mobile.di.module.ServerModule;
import com.chcit.mobile.mvp.common.contract.ServerContract;
import com.chcit.mobile.mvp.common.presenter.ServerPresenter;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ServerFragment extends SupportToolbarFragement<ServerPresenter> implements ServerContract.View {

    private static final int REQUEST_CODE_SCAN = 12 ;
    @BindView(R.id.et_server_address)
    SearchLayoutComponent etServerAddress;
    @BindView(R.id.btn_test_save)
    Button btnTestSave;
    @BindView(R.id.test_server_url)
    TextView testServerUrl;

    public static ServerFragment newInstance() {
        ServerFragment fragment = new ServerFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerServerComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .serverModule(new ServerModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_server, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(v->{
            startWithPop(LoginFragment.newInstance());
        });
        mCommonToolbar.getRightMenuView(0).setOnClickListener(v->{
            startWithPop(LoginFragment.newInstance());
        });

        etServerAddress.getImageEdit().setImageClick(l->{
            Intent intent = new Intent(mContext, CaptureActivity.class);
            /*ZxingConfig是配置类
             *可以设置是否显示底部布局，闪光灯，相册，
             * 是否播放提示音  震动
             * 设置扫描框颜色等
             * 也可以不传这个参数
             * */
            ZxingConfig config = new ZxingConfig();
            config.setPlayBeep(true);//是否播放扫描声音 默认为true
            config.setShake(true);//是否震动  默认为true
            config.setDecodeBarCode(true);//是否扫描条形码 默认为true
            config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
            config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
            config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
            config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
        });
    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        String serverUrl = SharedPreUtils.getInstance().getString(ConfigKeys.API_HOST.name(),"http://58.213.29.221:8090/yp-web/");
        testServerUrl.setText(serverUrl);
        etServerAddress.getImageEdit().setText(serverUrl);
    }

    @OnClick(R.id.btn_test_save)
    public void onViewClicked() {

        final String url = etServerAddress.getImageEdit().getText().toString();
        if (!URLUtil.isNetworkUrl(url)) {
            etServerAddress.getImageEdit().setError("URL地址不合法");
            return;
        }
        mPresenter.testAndSave(url);
    }

   /* private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            *//** EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*//*
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                btnTestSave.setEnabled(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            *//** EditText最初内容为空 改变EditText内容时 个数加一*//*
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount++;
                *//** 判断个数是否到达要求*//*
                *//* EditText总个数
                 *//* *//**
                 * EditText总个数
                 *//*int EDITTEXT_AMOUNT = 1;
                if (mEditTextHaveInputCount == EDITTEXT_AMOUNT) {
                    btnTestSave.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            serverUrl = s.toString().startsWith("http") ? s.toString() : "http://" + s.toString();
            testServerUrl.setText(serverUrl);

        }
    };
*/
    @Override
    public void toLoginPage() {
        testServerUrl.setText(etServerAddress.getImageEdit().getText());
        new MaterialDialog.Builder(mContext)
                .title("测试成功")
                .content("进入登录界面进行作业!")
                .positiveText("确定")
                .negativeText("取消")
               .onAny((dialog, which) -> {
                   dialog.dismiss();
                   if(which.equals(DialogAction.POSITIVE)){
                       SharedPreUtils.getInstance().putBoolean("FIRST", false);
                       startWithPop(LoginFragment.newInstance());
                   }

               }).autoDismiss(false)
                .show();

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                etServerAddress.getImageEdit().setText(content);
            }
        }
    }

}
